<?php
namespace App\Http\Logic;


use App\Enums\OrderEnum;
use App\Logic\BaseLogic;
use App\Logic\LogLogic;
use App\Models\SwtMachine;
use App\Models\SwtUser;
use App\Services\AliPayService;
use App\Services\WechatPayService;
use App\Services\ZhengYuanService;
use Illuminate\Support\Facades\DB;

class PayLogic extends BaseLogic {

    public static function goPay($order_info, $amount, $goods)
    {
        $machine_info = SwtMachine::firstWhere('id', $order_info['machine_id']);

        if($amount == 0) {//0元订单直接取消
            OrderLogic::cancelOrder($order_info['order_sn'], $order_info['door_num'], $order_info['platform']);
            return true;
        }

        switch( $order_info['platform'] )
        {
            case 'alipay' :
                $danger_amount = 10000;
            break;
            case 'wechat' :
                $danger_amount = 20000;
            break;
            case 'card' :
                $danger_amount = 0;
            break;
        }

        if($danger_amount > 0 && $amount > $danger_amount) { //超出订单标记异常
            OrderLogic::setAmountErrorOrder($order_info, $goods, $amount, $machine_info -> source_type);
            return true;
        }

        DB::beginTransaction();
        try {
            $res = OrderLogic::payOrder($order_info['id'], $amount, $goods, $machine_info -> source_type);

            if($res === false) {
                throw new \Exception(OrderLogic::getErrorMessage(), 500);
            }

            switch ($order_info['platform']) {
                case 'wechat' :
                    $service = new WechatPayService();
                    $pay_info = $service -> payOrder($order_info['order_sn'], $amount, $goods);
                    break;
                case 'alipay' :
                    $service = new AliPayService();
                    $pay_info = $service -> payOrder($order_info['order_sn'], $amount, $goods, $order_info['pay_order_id']);
                    break;
                case 'card' :
                    $pay_info = self::payByCard($order_info, $amount);
                    break;
            }

            if($pay_info['state_description'] !== OrderEnum::ORDER_MCH_COMPLETE) {
                throw new \Exception('Order Finish Error', 500);
            }

            //记录商品库存变更日志
            $log_goods = [];
            foreach($goods as $v) {
                $log_goods[] = [
                    'goods_name' => $v['name'],
                    'num'        => $v['quantity'],
                ];
            }

            LogLogic::setMachineGoodsLogs($order_info['machine_id'], $order_info['id'], $log_goods, '商品销售');

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            self::$error = $exception -> getMessage();
            return false;
        }
    }

    /**
     * @notes 直接发起一卡通支付
     * @param $order_info
     * @param $amount
     * @return array
     * @author Evil丿
     * @date 2025/01/07 17:38
     */
    public static function payByCard($order_info, $amount)
    {
        $amount /= 100;

        $user = SwtUser::firstWhere('id', $order_info['user_id']);

        $service = new ZhengYuanService();

        $per_data = $service -> prepay($user->card_id, $amount);

        $order_data = $service -> orderHandle($per_data['payId'], $order_info['order_sn']);

        $data = [
            'out_trade_no'   => $order_info['order_sn'],
            'pay_order_id'   => $per_data['payId'],
            'transaction_id' => $order_data['outTradeNo'],
            'receipt_amount' => $amount,
        ];

        $res = OrderLogic::finishOrder($data, 'card');

        if(!$res) {
            OrderLogic::setWarningOrder($order_info['order_sn'], $order_info['door_num'], '一卡通扣款异常：' . OrderLogic::getErrorMessage());
        } else {
            LogLogic::setZyLogs($order_info['order_sn'], $user->card_id, $amount, '订单付款');
        }

        return ['state_description' => OrderEnum::ORDER_MCH_COMPLETE];
    }
}
